package com.learn.demo.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 异步测试
 *
 * @author banjiawei
 * @date 2021/12/27
 */
@Service
@Slf4j
public class TestAsyncService {

    // 发送提醒短信 1
    public void service1() throws InterruptedException {
        log.info("--------start-service1------------");
        // 模拟耗时
        TimeUnit.SECONDS.sleep(5);
        log.info("--------end-service1------------");
    }

    // 发送提醒短信 2
    public void service2() throws InterruptedException {
        log.info("--------start-service2------------");
        // 模拟耗时
        TimeUnit.SECONDS.sleep(2);
        asyncService3();
        log.info("--------end-service2------------");
    }

    // （异步）发送提醒短信 1
    @Async
    public void asyncService1() throws InterruptedException {
        log.info("--------async start-service1------------");
        // 模拟耗时
        TimeUnit.SECONDS.sleep(5);
        log.info("--------async end-service1------------");
    }

    // （异步）发送提醒短信 2
    @Async
    public void asyncService2() throws InterruptedException {
        log.info("--------async start-service2------------");
        // 模拟耗时
        TimeUnit.SECONDS.sleep(2);
        asyncService3();
        log.info("--------async end-service2------------");
    }

    // （异步）发送提醒短信 2
    @Async
    public void asyncService3() throws InterruptedException {
        log.info("--------async start-service3------------");
        // 模拟耗时
        TimeUnit.SECONDS.sleep(3);
        log.info("--------async end-service3-----------");
    }

    @Async
    public Future<String> asyncService4() throws InterruptedException {
        log.info("--------async start-service4------------");
        // 模拟耗时
        TimeUnit.SECONDS.sleep(4);
        log.info("--------async end-service4-----------");

        return new AsyncResult("OK");
    }
}
